<?php
/**
 * Created by IntelliJ IDEA.
 * User: kha
 * Date: 10/4/13
 * Time: 8:56 PM
 * To change this template use File | Settings | File Templates.
 */

// TODO: Kha

/**
 * Request a SVN repo for group
 */

$group_guid = (int)get_input('group_guid');

$exec = 'find /opt/lampp/htdocs/igs/svnrepositories/ -type d -name ' . $group_guid;
$output = shell_exec($exec);

if ($output) {
    system_message(elgg_echo('groups:svn_request_already', array($group_guid)));
} else {

    // Get the group guid
    $group = get_entity($group_guid);

    if ($group->grouptype == SUBJECT_GROUP) {
        forward(REFERER);
    }

    if ($group->grouptype == NORMAL_GROUP) {
        $svn_agent = get_user_by_username('svnadmin');
    }

    if ($group->grouptype == PROJECT_GROUP) {
        $svn_agent = get_user($group->teacher_guid);
    }

    if (!$svn_agent) {
        register_error(elgg_echo("messages:user:nonexist"));
    }

    // compose the mesage
    // subject
    $subject = elgg_echo('groups:svn_request_message_title');

    // body
    $body = elgg_echo('groups:svn_request_message', array($group_guid));

    $user = elgg_get_logged_in_user_entity();
    $from = $user->guid;
    // send it
    $result = message_svn_send($group_guid, $subject, $body, $svn_agent->guid, $from, true, false);

    // check the sending
    if (!$result) {
        register_error(elgg_echo("messages:error"));
    }

    system_message(elgg_echo('groups:svn_request_success'));

    forward(REFERER);
}

//register_error(elgg_echo('group:notdeleted'));

// Check if there already is a repo for this group
// 1. Dirty way:
// Check the dir in /opt/usersvn/repositories whose name equal to the group's id

// linux shell command to execute

//$test = 'svnadmin create /opt/lampp/htdocs/igs/svnrepositories/' . $group_guid;
//$test = 'whoami';
//$a = shell_exec($test);
//var_dump($a);exit();
// execute the cmd and get output
//system_message($output);
// process the output
// empty => not found => request to the SVN operator (inbox message) => system message
// not empty => found => already request and proceeded => system message.

//send message to SVN Manager (svnadmin)
//    $svnadmin_username = 'svnadmin';
//    $user_svnadmin = get_user($group)

// check the svn user exists
//    if (!$user_svnadmin) {
//        register_error(elgg_echo("messages:user:nonexist"));
//    }


// 2. Optimized way: Check there is an annotation for this group that have the id 'group_repo_created' => Hard way
